package com.jinzhi.oss.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.oss.domain.FileDO;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.oss.service.OssService;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <pre>
 * 文件上传
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@RequestMapping("/common/sysFile")
public class FileController extends BaseController {

    @Autowired
    private FileService sysFileService;

    @Autowired
    private OssService ossService;


    private  String fastIp;


    private  String fastProt;


    private  String fastGroup;

    private String fastAil;

    @Autowired
    private  DictService dictService;

    public void fatInit(){

        Map map =new HashMap();
        map.put("type","fastdfs_group");
        map.put("name","fastdfs_group");
        fastGroup = dictService.selDicBy(map);

        map =new HashMap();
        map.put("type","fastdfs_prot");
        map.put("name","fastdfs_prot");
        fastProt = dictService.selDicBy(map);

        map =new HashMap();
        map.put("type","fastdfs_ip");
        map.put("name","fastdfs_ip");
        fastIp = dictService.selDicBy(map);

        map =new HashMap();
        map.put("type","fastAil_file");
        map.put("name","fastAil_file");
        fastAil = dictService.selDicBy(map);

    }


    //UPLOAD_PATH = ip + 服务端口 + 分组 + upload http://192.168.1.191:9999/group1/upload
    private String UPLOAD_PATH;


    @GetMapping()
    @RequiresPermissions("oss:file:file")




    String sysFile(Model model) {
        return "common/file/file";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("oss:file:list")
    public Result<Page<FileDO>> list(FileDO fileDTO) {
        Wrapper<FileDO> wrapper = new EntityWrapper<FileDO>(fileDTO);
        Page<FileDO> page = sysFileService.selectPage(getPage(FileDO.class), wrapper);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("oss:file:add")
    String add() {
        return "common/sysFile/add";
    }

    @GetMapping("/edit")
    @RequiresPermissions("oss:file:update")
    String edit(Long id, Model model) {
        FileDO sysFile = sysFileService.selectById(id);
        model.addAttribute("sysFile", sysFile);
        return "common/sysFile/edit";
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("oss:file:info")
    public Result<FileDO> info(@PathVariable("id") Long id) {
        FileDO sysFile = sysFileService.selectById(id);
        return Result.ok(sysFile);
    }

    /**
     * 保存
     */
    @Log("添加文件")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("oss:file:add")
    public Result<String> save(FileDO sysFile) {
        sysFileService.insert(sysFile);
        return Result.ok();
    }

    /**
     * 修改
     */
    @Log("更新文件")
    @RequestMapping("/update")
    @RequiresPermissions("oss:file:update")
    public Result<String> update(@RequestBody FileDO sysFile) {
        sysFileService.updateById(sysFile);
        return Result.ok();
    }

    /**
     * 删除
     */
    @Log("删除文件")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("oss:file:remove")
    public Result<String> remove(Long id) {
        sysFileService.deleteById(id);
        return Result.ok();
    }

    /**
     * 删除
     */
    @Log("批量删除文件")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("oss:file:remove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        sysFileService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }




////    阿里云
//    @Log("上传文件")
//    @ResponseBody
//    @PostMapping("/upload")
////    @RequiresPermissions("oss:file:add")
//    Result<String> upload(@RequestParam("file") MultipartFile file) {
//        String url  =ossService.uploadFileOss(file);
//        return Result.ok(url);
//    }
//





//    //本地对象存储
//    @Log("上传文件")
//    @ResponseBody
//    @PostMapping("/upload")
//    Result<String> upload(@RequestParam("file") MultipartFile file) {
//        fatInit(); //初始化
//
//        UPLOAD_PATH = "http://" + fastIp + ":" + fastProt + fastGroup;  //http://192.168.1.191:9999/group1/upload
//
//        String url = "";
//        try {
//            InputStreamResource isr = new InputStreamResource(file.getInputStream(),
//                    file.getOriginalFilename());
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            params.put("path", "86501729");
//            params.put("output", "json");
//            String resp = HttpUtils.post(UPLOAD_PATH, params,3000, 3000, "UTF-8");
//            Console.log("resp: {}", resp);
//
//
//            //取出上传结果
//            Map map = JSON.parseObject(resp, Map.class);
//            //取出最终的url路径
//            url = (String) map.get("url");
//            //将localhost替换为fast服务所在的ip地址
//            url = url.replace("localhost",fastIp);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return Result.ok(url);
//    }
//





    @Log("上传文件")
    @ResponseBody
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file")MultipartFile file) {
        fatInit();

        if(fastAil.equals("Ail")){
            String url  =ossService.uploadFileOss(file);
            return Result.ok(url);
        }else {
        UPLOAD_PATH = "http://" + fastIp + ":" + fastProt + fastGroup;
        String result = "";

        String url = "";
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse httpResponse = null;
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(200000)
                    .setSocketTimeout(2000000)
                    .build();
            HttpPost httpPost = new HttpPost(UPLOAD_PATH);
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setCharset(Charset.forName("UTF-8"))
                    .addTextBody("output", "json")
                    .addBinaryBody("file", file.getInputStream(),
                            ContentType.DEFAULT_BINARY, file.getOriginalFilename());
            httpPost.setEntity(multipartEntityBuilder.build());
            httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String respStr = EntityUtils.toString(httpResponse.getEntity());
                System.out.println(respStr);
                result = respStr;
            }

            httpClient.close();
            httpResponse.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //取出上传结果
        Map map = JSON.parseObject(result, Map.class);
        //取出最终的url路径
        url = (String) map.get("url");

        //http://192.168.1.191:9999/group1/default/20230609/03/18/4/文字样式.png?name=%E6%96%87%E5%AD%97%E6%A0%B7%E5%BC%8F.png
        String substring = url.substring(0, url.indexOf("&"));

        //9999/group1/default/20230609/03/18/4/文字样式.png?name=%E6%96%87%E5%AD%97%E6%A0%B7%E5%BC%8F.png
        String substring1 = substring.substring(substring.indexOf(fastProt),substring.length());
        substring1 = "http://" + fastIp + ":" + substring1;
        return Result.ok(substring1);
        }
    }


//    public static void main(String[] args) {
//        String a ="http://192.168.1.191:9999/group1/default/20230609/03/18/4/文字样式.png?name=%E6%96%87%E5%AD%97%E6%A0%B7%E5%BC%8F.png&download=1";
//
//
//        String substring = a.substring(0, a.indexOf("&"));
//
//        String substring1 = substring.substring(a.indexOf("9999"),substring.length());
//
//        System.out.println(substring);
//        System.out.println(substring1);
//    }


    @Log("上传图片保存到系统路径")
    @ResponseBody
    @PostMapping("/uploadAndSaveFile")
    public Result<String> uploadAndSaveFile(@RequestParam("file")MultipartFile file) throws  IOException {
        //判断用户是否上传了文件
        if(!file.isEmpty()){

            //文件上传的地址
            String path = ResourceUtils.getURL("classpath:").getPath()+"static/img";
            String realPath = path.replace('/', '\\').substring(1,path.length());
//            System.out.println(realPath);
            //获取文件的名称
            final String fileName = file.getOriginalFilename();

            //限制文件上传的类型
            String contentType = file.getContentType();
            if("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) || "image/png".equals(contentType) ){
                File files = new File(realPath,fileName);

                //完成文件的上传
                file.transferTo(files);
                System.out.println("图片上传成功!");
                return Result.ok(fileName);
            } else {
                return Result.fail("上传失败，不支持该类型！");
            }
        } else {
            return Result.fail("上传失败！");
        }
    }

}
